<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-form :inline="true" :model="formInline">
      <el-form-item label="请输入">
        <el-input placeholder="请输入" v-model="formInline.keyWord"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        align="center"
        v-for="item in tableLabel"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width ? item.width : 125"
      />
      <el-table-column fixed="right" label="Operations" min-width="120">
        <template #="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      background
      layout="prev, pager, next"
      size="small"
      :total="config.total"
      @current-change="handleChange"
    />
  </div>
  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    width="35%"
    :before-close="handleClose"
  >
    <!--
      需要注意的是设置了:inline="true",
      会对el-select的样式造成影响, 我们通过给他设置一个class=select-clearn
      在css进行处理
    -->
    <el-form :inline="true" :model="formUser" :rules="rules" ref="fromUserRef">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="formUser.name"
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input
              v-model.number="formUser.age"
              placeholder="请输入年龄"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="select-clearn" label="性别" prop="sex">
            <el-select v-model="formUser.sex" placeholder="请选择">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生日" prop="birth">
            <el-date-picker
              v-model="formUser.birth"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              width="100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="地址" prop="addr">
            <el-input
              v-model="formUser.addr"
              placeholder="请输入地址"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="justify-content: flex-end">
        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCurrentInstance, nextTick, onMounted, reactive, ref } from 'vue'

const { proxy } = getCurrentInstance()

// 1. 表单数据
const tableData = ref([])
const tableLabel = reactive([
  {
    prop: 'name',
    label: '姓名',
  },
  {
    prop: 'age',
    label: '年龄',
  },
  {
    prop: 'sexLabel',
    label: '性别',
  },
  {
    prop: 'birth',
    label: '出生日期',
    width: 200,
  },
  {
    prop: 'addr',
    label: '地址',
    width: 400,
  },
])
const getUserData = async () => {
  const data = await proxy.$api.getUserData(config)
  tableData.value = data.list.map((item) => ({
    ...item,
    sexLabel: item.sex === 1 ? '男' : '女',
  }))
  config.total = data.count
}

// 2. 搜索
const formInline = reactive({
  keyWord: '',
})
const config = reactive({
  name: '',
  total: 0,
  page: 1,
  pageSize: 10,
})
const handleSearch = () => {
  config.name = formInline.keyWord
  getUserData()
}

// 3. 翻页
const handleChange = (page) => {
  config.page = page
  getUserData()
}

// 4. 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('你确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await proxy.$api.deleteUser({ id: row.id })
    ElMessage({
      showClose: true,
      message: '删除成功',
      type: 'success',
    })
    getUserData()
  })
}

// 5. 新增用户
const action = ref('add')
const dialogVisible = ref(false)
const formUser = reactive({
  sex: '1',
})
const rules = reactive({
  name: [{ required: true, message: '姓名是必填项', trigger: 'blur' }],
  age: [
    { required: true, message: '年龄是必填项', trigger: 'blur' },
    { type: 'number', message: '年龄必须为数字值', trigger: 'blur' },
  ],
  sex: [{ required: true, message: '性别是必填项', trigger: 'change' }],
  birth: [{ required: true, message: '出生日期是必填项' }],
  addr: [{ required: true, message: '地址是必填项' }],
})

const handleClose = () => {
  dialogVisible.value = false
  // 重置表单数据
}
const handleCancel = () => {
  dialogVisible.value = false
}

const handleAdd = () => {
  dialogVisible.value = true
  action.value = 'add'
  proxy.$refs['fromUserRef'].resetFields()
}

// 点击编辑按钮
const handleEdit = (val) => {
  dialogVisible.value = true
  action.value = 'edit'
  nextTick(() => {
    Object.assign(formUser, { ...val, sex: '' + val.sex })
  })
}

const timeFormat = (time) => {
  let d = new Date(time)
  let year = d.getFullYear()
  let month = d.getMonth() + 1
  let date = d.getDate()
  function add(m) {
    return m < 10 ? '0' + m : m
  }
  return year + '-' + add(month) + '-' + add(date)
}
const onSubmit = () => {
  proxy.$refs['fromUserRef'].validate(async (valid) => {
    if (valid) {
      let res = null
      formUser.birth = /^\d{4}-\d{2}-\d{2}$/.test(formUser.birth)
        ? formUser.birth
        : timeFormat(formUser.birth)
      formUser.sex = parseInt(formUser.sex)
      if (action.value === 'add') {
        res = await proxy.$api.addUser(formUser)
      } else if (action.value === 'edit') {
        res = await proxy.$api.editUser(formUser)
      }
      if (res) {
        dialogVisible.value = false
        proxy.$refs['fromUserRef'].resetFields()
        getUserData()
      }
    } else {
      ElMessage({
        showClose: true,
        message: '请输入正确内容',
        type: 'error',
      })
    }
  })
}

onMounted(() => {
  getUserData()
})
</script>

<style lang="less" scoped>
.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.table {
  position: relative;
  height: 520px;
  .pagination {
    position: absolute;
    right: 10px;
    bottom: 30px;
  }
  .el-table {
    width: 100%;
    height: 500px;
  }
}
.select-clearn {
  display: flex;
}
</style>
